<?php

namespace App\V3\V3_2_7\Controllers;

use App\V3\V3_2_7\Models\AdminAddendumModel;
use App\V3\V3_2_7\Models\BarterModel;
use App\V3\V3_2_7\Models\BarterPayRecordModel;
use App\V3\V3_2_7\Models\MaterielPayHistoryModel;
use App\V3\V3_2_7\Models\OperMainAccountModel;
use App\V3\V3_2_7\Models\SellPayRecordModel;
use App\V3\V3_2_7\Models\StorageManageModel;
use App\V3\V3_2_7\Models\VipOrderModel;
use App\V3\V3_2_7\Models\VipSettingModel;
use App\Http\Controllers\Controller;
use App\V3\V3_2_7\Models\StorageSpaceOrderModel;
use App\V3\V3_2_7\Services\UploadImgService;
use Illuminate\Database\Query\Builder;
use Illuminate\Encryption\Encrypter;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use App\V3\V3_2_7\Models\SerialNumberModel;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use App\V3\V3_2_7\Models\StorageBatchModel;
use App\Services\MessageService;
use App\V3\V3_2_7\Models\AdminModel;
use App\V3\V3_2_7\Models\MaterielTypeModel;
use App\V3\V3_2_7\Models\PictureAlbumModel;
use App\V3\V3_2_7\Models\GoodsAlbumModel;
use App\V3\V3_2_7\Models\TextImageModel;
use App\V3\V3_2_7\Models\TextImageTemplatesModel;
use App\V3\V3_2_7\Models\SellModel;
use App\V3\V3_2_7\Models\SalesReturnModel;
use App\V3\V3_2_7\Models\TallyModel;
use App\V3\V3_2_7\Models\OverflowBreakageModel;
use App\V3\V3_2_7\Models\SealManageModel;
use App\V3\V3_2_7\Models\SellDriverModel;
use App\V3\V3_2_7\Models\MaterielModel;
use OSS\OssClient;
use SimpleSoftwareIO\QrCode\Facades\QrCode;


class CrontabController extends Controller
{
    public static function endExperience()
    {
        try {
            $userInstance = new AdminAddendumModel;
            $adminInfo = $userInstance::query()
                ->select(
                    'id',
                    'account_storage'
                )->where([
                    ['is_vip', '!=', 0],
                    ['vip_end_date', '<=', time()],
                ])
                ->get()->toArray();
            $notVipInfo = VipSettingModel::where('is_vip', 0)->first();
            $isVipInfo = VipSettingModel::query()->select('account_storage')
                ->where('is_vip', 1)->first();
            $distanceSpace = $isVipInfo['account_storage'] - $notVipInfo['account_storage'];
            $arr = [];
            foreach ($adminInfo as $key => $value) {
                $arr[$key] = [
                    'id' => $value['id'],
                    'is_vip' => 0,
                    'is_in_experience' => 1,
                    'is_end_experience' => 1,
                    'album_amount' => $notVipInfo['album_amount'],
                    'album_page_amount' => $notVipInfo['album_page_amount'],
                    'empty_bill_amount' => $notVipInfo['empty_bill_amount'],
                    'special_seal' => $notVipInfo['special_seal'],
                    'one_key_album_times' => $notVipInfo['one_key_album_times'],
                    'express_check_times' => $notVipInfo['express_check_times'],
                    'clear_watermark_or_not' => $notVipInfo['clear_watermark_or_not'],
                    'sub_account_number' => $notVipInfo['sub_account_number'],
                    'account_storage' => $notVipInfo['account_storage'],
                ];
                if ($value['account_storage'] > $notVipInfo['account_storage']) {
                    $arr[$key]['account_storage'] = $value['account_storage'] - $distanceSpace;
                }
            }
            if (!empty($arr)) {
                batch()->update($userInstance, $arr, 'id');
            }
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('脚本—结束vip体验：' . var_export($e->getMessage(), true));
            return false;
        }
    }

    public static function accountStorageStatus()
    {
        try {
            $arr1 = [];
            $arr2 = [];
            $t = strtotime(now()->subYear(1));//当前时间减去一年时间戳
            $adminAddendumInstance = new AdminAddendumModel;
            $storageSpaceOrderInstance = new StorageSpaceOrderModel;
            $list = $storageSpaceOrderInstance::query()->select(
                'a.id',
                'a.main_id',
                'account_storage',
                'username',
                'order_sn',
                'pay_time',
                'buy_storage_space',
                'c.gz_openid'
            )->from('storage_space_order as a')
                ->leftJoin('admin_addendum as b', 'b.main_id', '=', 'a.main_id')
                ->leftJoin('admin as c', 'c.id', '=', 'b.main_id')
                ->where([
                    ['pay_time', '<=', $t],
                    'is_expire' => 0,
                    'a.status' => 1,
                    'delete_flag' => 0,

                ])->get();
            if (!empty($list)) {
                foreach ($list->toArray() as $v) {
                    $account_storage = $v['account_storage'] - $v['buy_storage_space'] * 1024 * 1024;
                    if ($account_storage <= 0) $account_storage = 0;
                    $arr1[] = [
                        'main_id' => $v['main_id'],
                        'account_storage' => $account_storage
                    ];
                    $arr2[] = [
                        'id' => $v['id'],
                        'is_expire' => 1
                    ];
                    $orderSn = substr($v['order_sn'], 0, 2) . substr($v['order_sn'], (strlen($v['order_sn']) - 14), 14);
                    if (!empty($v['gz_openid'])) {
                        $mess = [
                            'time' => Carbon::parse($v['pay_time'])->format('Y年m月d日'),
                            'phone' => $v['username'],
                            'type' => '储存空间' . $v['buy_storage_space'] . 'M-过期提醒',
                            'mark' => '订单号：' . $orderSn,
                            'gz_openid' => $v['gz_openid']
                        ];
                        MessageService::buyerVipSpaceMessage($mess);
                    }
                }
                if (!empty($arr1)) {
                    batch()->update($adminAddendumInstance, $arr1, 'main_id');
                }
                if (!empty($arr2)) {
                    batch()->update($storageSpaceOrderInstance, $arr2, 'id');
                }
            }
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('脚本—实时监控客户存储空间状态：' . var_export($e->getMessage(), true));
            return false;
        }
    }

    public static function serialNumberAddMainId()
    {
        try {
            $SerialNumberModel = new SerialNumberModel();
            $list = $SerialNumberModel
                ->select('a.id', 'b.main_id')
                ->from('serial_number as a')
                ->leftJoin('storage_manage as b', 'b.id', '=', 'a.storage_manage_id')
                ->where('b.delete_flag', 0)
                ->where('a.main_id', 0)
                ->get();
            if (!empty($list->toArray())) {
                foreach ($list->toArray() as $v) {
                    $arr[] = [
                        'id' => $v['id'],
                        'main_id' => $v['main_id']
                    ];
                }
                if (!empty($arr)) {
                    batch()->update($SerialNumberModel, $arr, 'id');
                }
            }
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('脚本—给序列号批量添加主账号id：' . var_export($e->getMessage(), true));
            return false;
        }
    }

    /**
     * 定时脚本：发现达到预警的库存信息，加入标记，进行排序
     * Author: Sw
     * Created at 2023/2/25 17:13
     * @return bool
     */
    public static function transStorageAlertStatus()
    {
        try {
            //找到达到预警的库存信息
            $storageManageInfo = StorageManageModel::whereRaw('in_storage_num < alert_num')
                ->where('delete_flag', 0)
                ->get()->toArray();

            $storageManageId = [];
            foreach ($storageManageInfo as $value) {
                $storageManageId[] = $value['id'];
            }
            //达到预警的变更标记为已达到预警
            StorageManageModel::whereIn('id', $storageManageId)->where('delete_flag', 0)->update(['sort_flag' => 1]);
            //未达到预警的变更标记未已达到预警
            StorageManageModel::whereNotIn('id', $storageManageId)->where('delete_flag', 0)->update(['sort_flag' => 0]);

            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('脚本—发现达到预警的库存信息，加入标记，进行排序：' . var_export($e->getMessage(), true));
            return false;
        }
    }

    //批次号推送预警消息
    public static function storageBatchPuchAlterMessage()
    {
        try {
            $bathList = StorageBatchModel::select(
                'production_time',
                'expiration_date',
                'warning_time',
                'b.materiel_name',
                'b.storage_name',
                'c.gz_openid as main_openid',
                'a.batch_left_num',
                'a.batch_no',
                'b.type_name',
                'b.storage_id',
                'b.main_id',
                'e.gz_openid as storage_openid'
            )
                ->from('storage_batch as a')
                ->leftJoin('storage_manage as b', 'a.storage_manage_id', '=', 'b.id')
                ->leftJoin('admin as c', 'c.id', '=', 'a.main_id')
                ->leftJoin('storage as d', 'b.storage_id', '=', 'd.id')
                ->leftJoin('admin as e', 'e.id', '=', 'd.user_id')
                ->where([
                    'a.delete_flag' => 0,
                    'b.delete_flag' => 0,
                    'c.delete_flag' => 0,
                    'd.delete_flag' => 0,
                    'e.delete_flag' => 0,
                    ['c.gz_openid', '!=', ''],
                ])->get();
            if (!empty($bathList)) {
                $oneDay = 24 * 3600;
                foreach ($bathList->toArray() as $value) {
                    $value['type'] = 0;
                    $value['date'] = '';
                    if (!empty(floatval($value['batch_left_num']))) {
                        if (!empty($value['production_time'])) {
                            if (!empty($value['expiration_date']) && is_numeric($value['expiration_date'])) {//保质期
                                $expirationDate = $value['expiration_date'] * $oneDay;//保质期的时间戳
                                $expirationTime = strtotime($value['production_time']) + $expirationDate;//过期时间的时间戳
                                $timeRemaining = $expirationTime - time();//剩余时间
                                if (!empty($value['warning_time']) && is_numeric($value['warning_time']) && $timeRemaining > 0) {//预警时间设置
                                    $day = $timeRemaining / $oneDay;//剩余天数
                                    if ($day <= $value['warning_time']) {//将要到期，已经到了预警期
                                        //推送设置到预警时间的
                                        $value['date'] = date('Y/m/d', $expirationTime);
                                        $value['type'] = 1;
                                        $res = MessageService::sendStorageBatchAlertSms($value);
                                    }
                                } elseif ($timeRemaining <= 0) {//已经过期
                                    //推送设置到预警时间的
                                    $value['date'] = date('Y/m/d', $expirationTime);
                                    $value['type'] = 1;
                                    $res = MessageService::sendStorageBatchAlertSms($value);
                                }
                            }
                        }
                    } else {
                        //推送批次号剩余数量为0的
                        $value['type'] = 2;
                    }
                }
            }
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('脚本—批次号推送预警消息：' . var_export($e->getMessage(), true));
            return false;
        }
    }

    /**
     * 统计客户上传文件占用空间
     */
    public function statisticsFileSize()
    {
        ini_set("max_execution_time", 120);
        DB::beginTransaction();
        try {
            $adminList = AdminModel::query()->select(
                'id',
                'company_logo_img'
            )->where([
                'delete_flag' => 0,
                'is_active' => 1,
                'parent_id' => 0,
                ['company_logo_img', 'like', '%uploads/%']
            ])->get();
            $imgArr = [];
            if (!empty($adminList)) {
                foreach ($adminList->toArray() as $val) {
                    if (strpos($val['company_logo_img'], ',') !== false) {
                        $val['company_logo_img'] = array_filter(
                            explode(',',
                                $val['company_logo_img']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    $imgArr[] = [
                        'main_id' => $val['id'],
                        'img_list' => array_unique(array($val['company_logo_img']))
                    ];
                }
            }
            echo ('adminList====' . count($adminList->toArray())) . "<br/>";

            $goodsList = MaterielTypeModel::query()
                ->select(
                    'materiel_img',
                    'spec_img',
                    'materiel_img_group',
                    'main_id'
                )->from('materiel_type as a')
                ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
                ->where([
                    'a.delete_flag' => 0,
                    'b.delete_flag' => 0,
                    'b.is_active' => 1,
                    'b.parent_id' => 0,
                ])->where(function ($query) {
                    $query->orWhere('materiel_img', 'like', '%uploads/%');
                    $query->orWhere('spec_img', 'like', '%uploads/%');
                    $query->orWhere('materiel_img_group', 'like', '%uploads/%');
                })->get();

            if (!empty($goodsList)) {
                foreach ($goodsList->toArray() as $val) {
                    if (strpos($val['materiel_img'], ',') !== false) {
                        $val['materiel_img'] = array_filter(
                            explode(',',
                                $val['materiel_img']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    if (strpos($val['spec_img'], ',') !== false) {
                        $val['spec_img'] = array_filter(
                            explode(',',
                                $val['spec_img']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    if (strpos($val['materiel_img_group'], ',') !== false) {
                        $val['materiel_img_group'] = array_filter(
                            explode(',',
                                $val['materiel_img_group']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    $list = array_filter(array_merge(
                        is_array($val['materiel_img']) ? $val['materiel_img'] : array($val['materiel_img']),
                        is_array($val['materiel_img_group']) ? $val['materiel_img_group'] : array($val['materiel_img_group']),
                        is_array($val['spec_img']) ? $val['spec_img'] : array($val['spec_img']),
                    ));
                    $imgArr[] = [
                        'main_id' => $val['main_id'],
                        'img_list' => array_unique($list)
                    ];

                }
            }

            echo ('goodsList====' . count($goodsList->toArray())) . "<br/>";

            $pictureAlbumList = PictureAlbumModel::query()
                ->select(
                    'background_music',
                    'album_cover_img',
                    'main_id'
                )->from('picture_album as a')
                ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
                ->where([
                    'b.delete_flag' => 0,
                    'b.is_active' => 1,
                    'b.parent_id' => 0,
                ])->where(function ($query) {
                    $query->orWhere('background_music', 'like', '%uploads/%');
                    $query->orWhere('album_cover_img', 'like', '%uploads/%');
                })->get();

            if (!empty($pictureAlbumList)) {
                foreach ($pictureAlbumList->toArray() as $val) {
                    if (strpos($val['background_music'], ',') !== false) {
                        $pVal['background_music'] = array_filter(
                            explode(',',
                                $val['background_music']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    if (strpos($val['album_cover_img'], ',') !== false) {
                        $val['album_cover_img'] = array_filter(
                            explode(',',
                                $val['album_cover_img']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    $list = array_unique(array_filter(array_merge(
                        is_array($val['background_music']) ? $val['background_music'] : array($val['background_music']),
                        is_array($val['album_cover_img']) ? $val['album_cover_img'] : array($val['album_cover_img']),
                    )));
                    $imgArr[] = [
                        'main_id' => $val['main_id'],
                        'img_list' => $list
                    ];
                }
            }
            echo ('$pictureAlbumList====' . count($pictureAlbumList->toArray())) . "<br/>";


            $goodsAlbumList = GoodsAlbumModel::query()
                ->select(
                    'album_logo',
                    'background_music',
                    'album_cover_img',
                    'main_id'
                )->from('goods_album as a')
                ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
                ->where([
                    'b.delete_flag' => 0,
                    'b.is_active' => 1,
                    'b.parent_id' => 0,
                ])->where(function ($query) {
                    $query->orWhere('album_logo', 'like', '%uploads/%');
                    $query->orWhere('background_music', 'like', '%uploads/%');
                    $query->orWhere('album_cover_img', 'like', '%uploads/%');
                })->get();
            if (!empty($goodsAlbumList)) {
                foreach ($goodsAlbumList->toArray() as $val) {
                    if (strpos($val['album_logo'], ',') !== false) {
                        $val['album_logo'] = array_filter(
                            explode(',',
                                $val['album_logo']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    if (strpos($val['background_music'], ',') !== false) {
                        $val['background_music'] = array_filter(
                            explode(',',
                                $val['background_music']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    if (strpos($val['album_cover_img'], ',') !== false) {
                        $val['album_cover_img'] = array_filter(
                            explode(',',
                                $val['album_cover_img']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    $list = array_filter(array_merge_recursive(
                        array($val['album_logo']),
                        array($val['background_music']),
                        array($val['album_cover_img'])
                    ));
                    $imgArr[] = [
                        'main_id' => $val['main_id'],
                        'img_list' => $list
                    ];

                }
            }
            echo ('$goodsAlbumList====' . count($goodsAlbumList->toArray())) . "<br/>";


            $TextImageList = TextImageModel::query()
                ->select(
                    'background_music',
                    'album_cover_img',
                    'main_id'
                )->from('text_image as a')
                ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
                ->where([
                    'b.delete_flag' => 0,
                    'b.is_active' => 1,
                    'b.parent_id' => 0,
                ])->where(function ($query) {
                    $query->orWhere('background_music', 'like', '%uploads/%');
                    $query->orWhere('album_cover_img', 'like', '%uploads/%');
                })->get();
            if (!empty($TextImageList)) {
                foreach ($TextImageList->toArray() as $val) {
                    if (strpos($val['background_music'], ',') !== false) {
                        $val['background_music'] = array_filter(
                            explode(',',
                                $val['background_music']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    if (strpos($val['album_cover_img'], ',') !== false) {
                        $val['album_cover_img'] = array_filter(
                            explode(',',
                                $val['album_cover_img']),
                            function ($v) {
                                return $v !== '';
                            });
                    }

                    $list = array_unique(array_filter(array_merge_recursive(
                        is_array($val['background_music']) ? $val['background_music'] : array($val['background_music']),
                        is_array($val['album_cover_img']) ? $val['album_cover_img'] : array($val['album_cover_img']),
                    )));
                    $imgArr[] = [
                        'main_id' => $val['main_id'],
                        'img_list' => $list
                    ];
                }
            }
            echo ('$TextImageList====' . count($TextImageList->toArray())) . "<br/>";

            $TextImageTemplateList = TextImageTemplatesModel::query()
                ->select(
                    'temp_img_video_01',
                    'temp_img_video_02',
                    'main_id'
                )->from('album_content_template as a')
                ->leftJoin('text_image as b', 'b.id', '=', 'a.pa_id')
                ->leftJoin('admin as c', 'c.id', '=', 'b.main_id')
                ->where([
                    'c.delete_flag' => 0,
                    'c.is_active' => 1,
                    'c.parent_id' => 0,
                ])->where(function ($query) {
                    $query->orWhere('temp_img_video_01', 'like', '%uploads/%');
                    $query->orWhere('temp_img_video_02', 'like', '%uploads/%');
                })->get();
            if (!empty($TextImageTemplateList)) {
                foreach ($TextImageTemplateList->toArray() as $val) {
                    if (strpos($val['temp_img_video_01'], ',') !== false) {
                        $val['temp_img_video_01'] = array_filter(
                            explode(',',
                                $val['temp_img_video_01']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    if (strpos($val['temp_img_video_02'], ',') !== false) {
                        $val['temp_img_video_02'] = array_filter(
                            explode(',',
                                $val['temp_img_video_02']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    $list = array_unique(array_filter(array_merge_recursive(
                        is_array($val['temp_img_video_01']) ? $val['temp_img_video_01'] : array($val['temp_img_video_01']),
                        is_array($val['temp_img_video_02']) ? $val['temp_img_video_02'] : array($val['temp_img_video_02']),
                    )));
                    $imgArr[] = [
                        'main_id' => $val['main_id'],
                        'img_list' => $list
                    ];
                }
            }
            echo ('$TextImageTemplateList====' . count($TextImageTemplateList->toArray())) . "<br/>";

            $sellList = SellModel::query()->select(
                'proof_image',
                'main_id'
            )->from('sell as a')
                ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
                ->where([
                    'b.delete_flag' => 0,
                    'b.is_active' => 1,
                    'b.parent_id' => 0,
                    'a.delete_flag' => 0,
                    ['proof_image', 'like', '%uploads/%']
                ])->get();
            if (!empty($sellList)) {
                foreach ($sellList->toArray() as $val) {
                    if (strpos($val['proof_image'], ',') !== false) {
                        $val['proof_image'] = array_filter(
                            explode(',',
                                $val['proof_image']),
                            function ($v) {
                                return $v !== '';
                            });
                    }

                    $list = array_unique(
                        is_array($val['proof_image']) ? $val['proof_image'] : array($val['proof_image'])
                    );
                    $imgArr[] = [
                        'main_id' => $val['main_id'],
                        'img_list' => $list
                    ];
                }
            }
            echo ('$sellList====' . count($sellList->toArray())) . "<br/>";

            $salesReturnList = SalesReturnModel::query()
                ->select(
                    'proof_image',
                    'main_id'
                )->from('sales_return as a')
                ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
                ->where([
                    'b.delete_flag' => 0,
                    'b.is_active' => 1,
                    'b.parent_id' => 0,
                    'a.delete_flag' => 0,
                    ['proof_image', 'like', '%uploads/%'],
                    ['barter_return_no', '!=', '']
                ])->get();//退货表中的包含图片的参数
            if (!empty($salesReturnList)) {
                foreach ($salesReturnList->toArray() as $val) {
                    if (strpos($val['proof_image'], ',') !== false) {
                        $val['proof_image'] = array_filter(
                            explode(',',
                                $val['proof_image']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    $list = array_unique(
                        is_array($val['proof_image']) ? $val['proof_image'] : array($val['proof_image'])
                    );
                    $imgArr[] = [
                        'main_id' => $val['main_id'],
                        'img_list' => $list
                    ];
                }
            }
            echo ('$salesReturnList====' . count($salesReturnList->toArray())) . "<br/>";

            $tallyList = TallyModel::query()->select(
                'proof_image',
                'main_id'
            )->from('tally as a')
                ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
                ->where([
                    'b.delete_flag' => 0,
                    'b.is_active' => 1,
                    'b.parent_id' => 0,
                    'a.delete_flag' => 0,
                    ['proof_image', 'like', '%uploads/%'],
                ])->get();//记账表中的包含图片的参数
            if (!empty($tallyList)) {
                foreach ($tallyList->toArray() as $val) {
                    if (strpos($val['proof_image'], ',') !== false) {
                        $val['proof_image'] = array_filter(
                            explode(',',
                                $val['proof_image']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    $list = array_unique(
                        is_array($val['proof_image']) ? $val['proof_image'] : array($val['proof_image'])
                    );
                    $imgArr[] = [
                        'main_id' => $val['main_id'],
                        'img_list' => $list
                    ];
                }
            }
            echo ('$tallyList====' . count($tallyList->toArray())) . "<br/>";

            $overflowBreakageList = OverflowBreakageModel::query()
                ->select(
                    'proof_image',
                    'main_id'
                )->from('overflow_breakage as a')
                ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
                ->where([
                    'b.delete_flag' => 0,
                    'b.is_active' => 1,
                    'b.parent_id' => 0,
                    'a.delete_flag' => 0,
                    ['proof_image', 'like', '%uploads/%'],
                ])->get();//报溢报损主单表中的包含图片的参数
            if (!empty($overflowBreakageList)) {
                foreach ($overflowBreakageList->toArray() as $val) {
                    if (strpos($val['proof_image'], ',') !== false) {
                        $val['proof_image'] = array_filter(
                            explode(',',
                                $val['proof_image']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    $list = array_unique(
                        is_array($val['proof_image']) ? $val['proof_image'] : array($val['proof_image'])
                    );
                    $imgArr[] = [
                        'main_id' => $val['main_id'],
                        'img_list' => $list
                    ];
                }
            }
            echo ('$overflowBreakageList====' . count($overflowBreakageList->toArray())) . "<br/>";

            $materielList = MaterielModel::query()->select(
                'proof_image',
                'main_id'
            )->from('materiel as a')
                ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
                ->where([
                    'b.delete_flag' => 0,
                    'b.is_active' => 1,
                    'b.parent_id' => 0,
                    'a.delete_flag' => 0,
                    ['proof_image', 'like', '%uploads/%'],
                ])->get();//物料管理表中的包含图片的参数
            if (!empty($materielList)) {
                foreach ($materielList->toArray() as $val) {
                    if (strpos($val['proof_image'], ',') !== false) {
                        $val['proof_image'] = array_filter(
                            explode(',',
                                $val['proof_image']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    $list = array_unique(
                        is_array($val['proof_image']) ? $val['proof_image'] : array($val['proof_image'])
                    );
                    $imgArr[] = [
                        'main_id' => $val['main_id'],
                        'img_list' => $list
                    ];
                }
            }
            echo ('$materielList====' . count($materielList->toArray())) . "<br/>";

            $sealList = SealManageModel::query()->select(
                'seal_img',
                'main_id'
            )->from('seal_manage as a')
                ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
                ->where([
                    'b.delete_flag' => 0,
                    'b.is_active' => 1,
                    'b.parent_id' => 0,
                    ['seal_img', 'like', '%uploads/%'],
                ])->get();//印章管理表中的包含图片的参数
            if (!empty($sealList)) {
                foreach ($sealList->toArray() as $val) {
                    if (strpos($val['seal_img'], ',') !== false) {
                        $val['seal_img'] = array_filter(
                            explode(',',
                                $val['seal_img']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    $list = array_unique(
                        is_array($val['seal_img']) ? $val['seal_img'] : array($val['seal_img'])
                    );
                    $imgArr[] = [
                        'main_id' => $val['main_id'],
                        'img_list' => $list
                    ];
                }
            }
            echo ('$sealList====' . count($sealList->toArray())) . "<br/>";

            $driverList = SellDriverModel::query()
                ->select(
                    'plate_image',
                    'id_card_image',
                    'driving_licence',
                    'main_id'
                )->from('sell_driver as a')
                ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
                ->where([
                    'b.delete_flag' => 0,
                    'b.is_active' => 1,
                    'b.parent_id' => 0,
                ])->where(function ($query) {
                    $query->orWhere('plate_image', 'like', '%uploads/%');
                    $query->orWhere('id_card_image', 'like', '%uploads/%');
                    $query->orWhere('driving_licence', 'like', '%uploads/%');
                })->get();//印章管理表中的包含图片的参数
            if (!empty($driverList)) {
                foreach ($driverList->toArray() as $val) {
                    if (strpos($val['plate_image'], ',') !== false) {
                        $val['plate_image'] = array_filter(
                            explode(',',
                                $val['plate_image']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    if (strpos($val['id_card_image'], ',') !== false) {
                        $val['id_card_image'] = array_filter(
                            explode(',',
                                $val['id_card_image']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    if (strpos($val['driving_licence'], ',') !== false) {
                        $val['driving_licence'] = array_filter(
                            explode(',',
                                $val['driving_licence']),
                            function ($v) {
                                return $v !== '';
                            });
                    }
                    $list = array_unique(array_filter(array_merge_recursive(
                        is_array($val['plate_image']) ? $val['plate_image'] : array($val['plate_image']),
                        is_array($val['id_card_image']) ? $val['id_card_image'] : array($val['id_card_image']),
                        is_array($val['driving_licence']) ? $val['driving_licence'] : array($val['driving_licence']),
                    )));

                    $imgArr[] = [
                        'main_id' => $val['main_id'],
                        'img_list' => $list
                    ];
                }

            }
            echo ('$driverList====' . count($driverList->toArray())) . "<br/>";

            $iData = [];
            if (!empty($imgArr)) {
                $ossclient = new OssClient(
                    config('app.aliyun_oss_key'),
                    config('app.aliyun_oss_secret'),
                    config('app.aliyun_oss_endpoint')
                );//创建oss对象
                foreach ($imgArr as $iVal) {
                    foreach ($iVal['img_list'] as $lVal) {
                        $iData[$iVal['main_id']][] = $lVal;
                    }

                    $iData[$iVal['main_id']] = array_unique($iData[$iVal['main_id']]);
                }
                if (!empty($iData)) {
                    // dump_dug($iData);
                    $fileSizeData = [];
                    foreach ($iData as $dKey => $dVal) {
                        $totalSize = 0;
                        foreach ($dVal as $item) {
                            if (strpos($item, 'uploads/') !== false) {
                                $path = strstr($item, 'uploads/');
                                try {
                                    $imgInfo = $ossclient->getObjectMeta(config('app.aliyun_oss_bucket'), $path);
                                    $totalSize += $imgInfo['content-length'];
                                } catch (\Exception $e) {

                                }
                            }
                        }
                        $fileSizeData[] = [
                            'main_id' => $dKey,
                            'statistics_file_size' => $totalSize
                        ];
                    }
                    dump_dug($fileSizeData);
                    if (!empty($fileSizeData)) {
                        batch()->update(new AdminAddendumModel(), $fileSizeData, 'main_id');
                    }
                }
            }
            dump_dug(22);
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('统计客户使用OSS空间更新占用空间异常：' . var_export($e->getMessage(), true));
        }
    }

    //订单欠款提醒（销售/换货/采购）
    public static function debtReminderMessage()
    {
        try {
            $t = strtotime(Carbon::now()->toDateString() . ' 23:59:59');
            $sellList = SellModel::query()
                ->select(
                    'a.id',
                    'order_no',
                    'username',
                    'gz_openid',
                    "final_money",
                    "debt_reminder_time",
                    "name",
                    "other_charges"
                )
                ->from('sell as a')
                ->leftJoin('admin as b', 'a.main_id', '=', 'b.id')
                ->leftJoin('supplier_customer as c', 'a.customer_id', '=', 'c.id')
                ->where([
                    'repeal_status' => 0,
                    'a.delete_flag' => 0,
                    'b.delete_flag' => 0,
                    'c.delete_flag' => 0,
                    ['pay_status', '!=', 2],
                    ['gz_openid', '!=', ''],
                    ['debt_reminder_time', '<', $t],
                ])->get();
            if (!empty($sellList)) {//销售欠款提醒推送
                foreach ($sellList->toArray() as $sVal) {
                    $totalMoney = SellPayRecordModel::where(['sell_id' => $sVal['id']])->sum('expend');
                    if (!empty($totalMoney)) {
                        $sVal['debt'] = floatval($sVal['final_money'] + $sVal['other_charges'] - $totalMoney);
                        if ($sVal['debt'] <= 0) $sVal['debt'] = 0;
                    } else {
                        $sVal['debt'] = $sVal['final_money'];
                    }
                    $start = Carbon::parse($sVal['debt_reminder_time'])->format('Y-m-d');
                    $end = Carbon::parse()->format('Y-m-d');
                    $days = Carbon::parse($start)->diffInDays($end);
                    $sVal['day'] = $days;
                    $sVal['time'] = Carbon::parse($sVal['debt_reminder_time'])->format('Y年m月d日');
                    $sVal['remark'] = '欠款';
                    $sVal['name'] = '客户:' . $sVal['name'] . '-销售欠款过期' . $days . '天';
                    $res = MessageService::debtReminderMessage($sVal);
                }
            }
            $barterList = BarterModel::query()
                ->select(
                    'a.id',
                    'order_no',
                    'username',
                    'gz_openid',
                    "spread_price",
                    "debt_reminder_time",
                    "name",
                    "other_charges"
                )
                ->from('barter as a')
                ->leftJoin('admin as b', 'a.main_id', '=', 'b.id')
                ->leftJoin('supplier_customer as c', 'a.customer_id', '=', 'c.id')
                ->where([
                    'repeal_status' => 0,
                    'a.delete_flag' => 0,
                    'b.delete_flag' => 0,
                    'c.delete_flag' => 0,
                    ['pay_status', '!=', 2],
                    ['gz_openid', '!=', ''],
                    ['debt_reminder_time', '!=', ''],
                    ['debt_reminder_time', '<', $t],
                ])->get();

            if (!empty($barterList)) {//销售欠款提醒推送
                foreach ($barterList->toArray() as $bVal) {
                    if (!BarterPayRecordModel::query()->where(['barter_id' => $bVal['id']])->exists()) {
                        $bVal['debt'] = $bVal['spread_price'] + $bVal['other_charges'];
                        $type = $bVal['debt'] >= 0 ? '退款' : '收款';
                        $bVal['debt'] = abs($bVal['debt']);
                        $start = Carbon::parse($bVal['debt_reminder_time'])->format('Y-m-d');
                        $end = Carbon::parse()->format('Y-m-d');
                        $days = Carbon::parse($start)->diffInDays($end);
                        $bVal['time'] = Carbon::parse($bVal['debt_reminder_time'])->format('Y年m月d日');
                        $bVal['remark'] = $type;
                        $bVal['name'] = '客户:' . $bVal['name'] . '-退换货欠款过期' . $days . '天';
                        MessageService::debtReminderMessage($bVal);
                    }
                }
            }

            $materielList = MaterielModel::query()
                ->select(
                    'a.id',
                    'purchase_no as order_no',
                    'username',
                    'gz_openid',
                    "final_money",
                    "debt_reminder_time",
                    "name",
                    "other_charges"
                )
                ->from('materiel as a')
                ->leftJoin('admin as b', 'a.main_id', '=', 'b.id')
                ->leftJoin('supplier_customer as c', 'a.supplier_customer_id', '=', 'c.id')
                ->where([
                    'repeal_status' => 0,
                    'a.delete_flag' => 0,
                    'b.delete_flag' => 0,
                    'c.delete_flag' => 0,
                    ['pay_status', '!=', 2],
                    ['gz_openid', '!=', ''],
                    ['debt_reminder_time', '!=', ''],
                    ['debt_reminder_time', '<', $t]
                ])->get();
            if (!empty($materielList)) {//采购待付提醒推送
                foreach ($materielList->toArray() as $mVal) {
                    $totalMoney = MaterielPayHistoryModel::where(['materiel_id' => $mVal['id']])->sum('money');
                    if (!empty($totalMoney)) {
                        $mVal['debt'] = floatval($mVal['final_money'] + $mVal['other_charges'] - $totalMoney);
                        if ($mVal['debt'] <= 0) $mVal['debt'] = 0;
                    } else {
                        $mVal['debt'] = $mVal['final_money'];
                    }
                    $start = Carbon::parse($mVal['debt_reminder_time'])->format('Y-m-d');
                    $end = Carbon::parse()->format('Y-m-d');
                    $days = Carbon::parse($start)->diffInDays($end);
                    $mVal['day'] = $days;
                    $mVal['time'] = Carbon::parse($mVal['debt_reminder_time'])->format('Y年m月d日');
                    $mVal['remark'] = '待付';
                    $mVal['name'] = '客户:' . $mVal['name'] . '-采购欠款过期' . $days . '天';
                    $res = MessageService::debtReminderMessage($mVal);
                }
            }
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('脚本—订单欠款提醒（销售/换货/采购）：' . var_export($e->getMessage(), true));
            return false;
        }
    }

    public static function buyerVipSpaceMessage()
    {
        try {
            $t = strtotime(Carbon::now()->toDateString() . ' 00:00:00');
            $adminInfo = AdminAddendumModel::query()->select(
                'a.id',
                'gz_openid',
                'username',
                'is_first_charge',
                'vip_end_date',
                'is_in_experience',
                'is_end_experience',
                'first_charge_price',

            )->from('admin_addendum as a')
                ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
                ->where([
                    'delete_flag' => 0,
                    'is_vip' => 1,
                    ['gz_openid', '!=', ''],
                    ['vip_end_date', '>=', $t],
                ])->get();
            if (!empty($adminInfo)) {
                $vipSetInfo = VipSettingModel::query()->select(
                    'open_vip_cost',
                    'first_charge_price'
                )->where(['is_vip' => 1])->first();
                $title = '购买到期';
                foreach ($adminInfo->toArray() as $aVal) {
                    if (!empty($aVal['is_in_experience']) && empty($aVal['is_end_experience']) && !empty(floatval($aVal['first_charge_price']))) {
                        if (floatval($aVal['first_charge_price']) == floatval($vipSetInfo['first_charge_price'])) {//首次购买VIP到期
                            $title = 'VIP首充';
                        } elseif (floatval($aVal['first_charge_price']) == floatval($vipSetInfo['open_vip_cost'])) {//多次购买VIP到期
                            $title = 'VIP会员';
                        }
                    } elseif (!empty($aVal['is_in_experience']) && empty($aVal['is_end_experience']) && empty(floatval($aVal['first_charge_price']))) {//免费体验VIP到期
                        $title = '免费VIP体验';
                    }
                    $start = Carbon::parse($aVal['vip_end_date'])->format('Y-m-d');
                    $end = Carbon::parse()->format('Y-m-d');
                    $days = Carbon::parse($start)->diffInDays($end);
                    if ($days >= 0 && $days <= 7) {//7天内VIP到期提醒
                        $remark = '还有' . $days . '天到期，请立即充值！';
                        if ($days == 0) $remark = '今日到期，请立即充值！';
                        $mess = [
                            'time' => Carbon::parse($aVal['vip_end_date'])->format('Y年m月d日'),
                            'phone' => $aVal['username'],
                            'type' => $title,
                            'mark' => $remark,
                            'gz_openid' => $aVal['gz_openid']
                        ];
                        MessageService::buyerVipSpaceMessage($mess);
                    }
                }
            }
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('脚本—订单欠款提醒（销售/换货/采购）：' . var_export($e->getMessage(), true));
            return false;
        }
    }

    public static function updGoodsImg()
    {
        $list = MaterielTypeModel::query()
            ->where('materiel_img', 'like', ',/%')
            ->where('delete_flag', 0)
            ->get();
        try {
            if (!empty($list->toArray())) {
                foreach ($list as $val) {
                    $imgArr = explode(',', $val['materiel_img']);
                    if (empty($imgArr[0]) && !empty($imgArr[1])) {
                        $val->materiel_img = $imgArr[1];
                        $val->save();
                    }
                }
            }
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('脚本—修改图片路径带号：' . var_export($e->getMessage(), true));
            return false;
        }
    }

    /**
     *仓库虚拟库位归零 - 脚步
     * Author: zlf
     * Created at 2024/5/31 10:53
     * @return bool
     */
    public static function delWarehouseVirtualInventory()
    {
        $sellList = SellModel::query()
            ->select(
                'main_id',
                'a.id as sell_id',
                'out_status',
                'username',
                'nickname'
            )->from("sell as a")
            ->leftJoin('admin as b', 'b.id', '=', 'a.main_id')
            ->where([
                'a.delete_flag' => 0,
                'repeal_status' => 0,
                ['out_status', '!=', 2],
                'b.delete_flag' => 0,
                'b.is_active' => 1,
                'parent_id' => 0
            ])->groupBy('main_id')
            ->get();

        DB::beginTransaction();
        try {
            if (!empty($sellList->toArray())) {
                $mainIdArr = array_column($sellList->toArray(), 'main_id');
                StorageManageModel::query()
                    ->whereNotIn('main_id', $mainIdArr)
                    ->where([
                        'delete_flag' => 0
                    ])->update(['virtual_storage_num' => 0]);
            }
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('仓库虚拟库位归零异常：' . var_export($e->getMessage(), true));
            return false;
        }
    }

    /**
     *删除垃圾图片 - 脚步
     * Author: zlf
     * Created at 2024/6/17 9:46
     * @return bool
     */
    public static function delUploadImgScript(): bool
    {
        try {
            UploadImgService::handleImg();
            return true;
        } catch (\Exception $e) {
            Log::debug("脚步-删除垃圾图片异常：" . var_export($e->getMessage(), true));
            return false;
        }
    }

    /**
     *图片数据处理
     * Author: zlf
     * Created at 2024/3/6 16:56
     * @param $model
     * @param $param
     * @return array
     */
    public static function imgDataHandle($model, $param)
    {
        $imgArr = [];
        if (!empty($model)) {
            foreach ($model->toArray() as $val) {
                if (strpos($val[$param], ',') !== false) {
                    $val[$param] = array_filter(explode(',', $val[$param]),
                        function ($v) {
                            return $v !== '';
                        });
                }
                $imgArr[] = [
                    'main_id' => $val['main_id'],
                    'img_list' => array($val[$param])
                ];

            }
        }
        return $imgArr;
    }

    /**
     *删除主账号使用负数库存表记录
     * Author: zlf
     * Created at 2024/7/10 15:15
     * @return bool
     */
    public static function delOperMainAccount(): bool
    {
        $accountIds = OperMainAccountModel::query()
            ->where([
                'delete_flag' => 0
            ])->pluck('main_id');
        if ($accountIds !== null) {
            $mainIds = AdminAddendumModel::query()
                ->whereIn('main_id', $accountIds->toArray())
                ->where(['is_vip' => 0])
                ->pluck('main_id');
            if ($mainIds !== null) {
                OperMainAccountModel::query()
                    ->whereIn('main_id', $mainIds->toArray())
                    ->update(['delete_flag' => 1]);
            }
        }
        return true;
    }
}
